package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Joiner;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.IIotAgencyService;
import com.pms.service.IIotRepairDeclareService;
import com.pms.service.IIotRepairMaintenanceService;
import com.pms.service.IIotWaterPumpGroupService;
import com.pms.util.PhoneUtils;
import com.pms.util.idutil.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/iotRepairDeclare")
@Api(value="二汞设备保修申报表",description = "二汞设备保修申报表")
public class IotRepairDeclareController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IIotRepairDeclareService iotRepairDeclareService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IIotRepairMaintenanceService iotRepairMaintenanceService;
    @Autowired
    IIotAgencyService orgService;
    /**
     * 添加申报二汞水泵组维修
     * @param groupId
     * @param declareType
     * @param declarePerson
     * @param declarePhone
     * @param description
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加申报二汞水泵组维修")
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupId",value="水泵组ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="roleId",value="角色ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="declareType",value="1.未知2.设备故障3.环境因素",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="declarePerson",value="申报人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="declarePhone",value="申报人电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="故障描述",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="系统编码",required = true,dataType = "String",paramType="form"),
    })
    public R add(Long roleId,Long groupId, Integer declareType,String declarePerson, String declarePhone, String description,Long agencyId,String companyCode){
         parameterIsNull(groupId,"请填写水泵组ID");
        parameterIsNull(declareType,"请填写故障类型");
        parameterIsNull(declarePerson,"请填写申报人");
        parameterIsNull(declarePhone,"请填写申报人电话");
        parameterIsNull(description,"请填写故障描述");
        parameterIsNull(agencyId,"请填写机构ID");

        parameterIsNull(roleId,"请填写角色ID");
        parameterIsNull(companyCode,"请填写系统编码");
        Boolean is= PhoneUtils.isPhone(declarePhone);
        if(is==false){return  R.error(400,"申报人电话格式错误");}
        IotRepairDeclare entity=new IotRepairDeclare();
        IotAgency  agency = orgService.selectById(agencyId);
        parameterIsNull(agency,"机构信息不存在");
        if (agency.getLevel()==2){
            entity.setAgencyId(agencyId);
        }else  if (agency.getLevel()==3){
            entity.setAgencyId(agency.getParentId());
            entity.setCommunityId(agency.getId());
        }else  if (agency.getLevel()==4){
            IotAgency  parentAgency = orgService.selectById(agency.getParentId());
            parameterIsNull(parentAgency,"小区机构信息不存在");
            entity.setAgencyId(parentAgency.getParentId());
            entity.setCommunityId(agency.getParentId());
            entity.setHouseId(agency.getId());
        }
        entity.setCompanyCode(companyCode);
        IotRepairDeclare declare=iotRepairDeclareService.selectOne(new EntityWrapper<IotRepairDeclare>().eq("group_id",groupId).and().eq("state_",1));
        if (declare!=null){return  R.error(400,"该水泵组已申报,请查看");}
        IotWaterPumpGroup eq=waterPumpGroupService.selectById(groupId);
        if (eq==null){return  R.error(400,"水泵组信息不存在");}
        Map<String,String> currentUserMap = getCurrentUserMap();
        entity.setGroupName(eq.getName());//水泵组名称
        entity.setBelongedCommunity(eq.getCommunityName());//所属小区
        entity.setBelongedHouse(eq.getParentName());//所属水泵房
        entity.setDeclareType(declareType);//故障类型
        entity.setRoleId(Long.parseLong(currentUserMap.get("roleId")));//角色ID
        entity.setDeclarePerson(declarePerson);//申报人
        entity.setDeclarePhone(declarePhone);//申报人电话
        entity.setDescription(description);//故障描述
        entity.setGroupId(groupId);//设备ID
        entity.setTarget(2);
        entity.setDeclareData(new Date());//申报时间
        entity.setRoleId(roleId);
        entity.setState(1);//状态1待处理2拒绝受理3已受理
        entity.setCrtTime(new Date());//创建时间
        entity.setIsRead(2);//是否已读(1已读2未读)
        iotRepairDeclareService.insert(entity);
        return R.ok();
    }

    /**
     * 查询申报二汞水泵组维修信息
     * @param repairDeclareId
     * @return
     */
    @ApiOperation(value = "查询申报二汞水泵组维修信息")
    @GetMapping(value = "/findById")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form"),
    })
    public R findById(@RequestParam Long repairDeclareId){
        parameterIsNull(repairDeclareId,"设备保修申报ID不能为空");
        IotRepairDeclare repair= iotRepairDeclareService.selectById(repairDeclareId);
        return R.ok().put("data",repair);
    }

    /**
     * 添加受理申报信息
     * @param acceptPerson
     * @param acceptPhone
     * @return
     */
    @ApiOperation(value = "添加受理申报信息")
    @PostMapping("/addAcceptPerson")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报水泵组维修ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="acceptPerson",value="受理人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="acceptPhone",value="受理人电话",required = true,dataType = "String",paramType="form"),
    })
    public R addAcceptPerson(String repairDeclareId,String acceptPerson,String acceptPhone){
        parameterIsNull(repairDeclareId,"设备保修申报ID不能为空");
        parameterIsNull(acceptPerson,"受理人不能为空");
        parameterIsNull(acceptPhone,"受理人电话不能为空");
        Boolean is=PhoneUtils.isPhone(acceptPhone);
        if(is==false){return  R.error(400,"受理人电话格式错误");}
        IotRepairDeclare repair=iotRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        if (repair.getState()==3){
            return  R.error(400,"该条申报信息已受理,请修改");
        }
        repair.setAcceptPerson(acceptPerson);//受理人
        repair.setAcceptPhone(acceptPhone);//受理电话
        repair.setAcceptData(new Date());//受理时间
        repair.setState(3);//修改状态为已受理
        repair.setIsRead(2);
        repair.setUpdTime(new Date());//修改时间
        repair.setCrtUser(getCurrentUserMap().get("userName"));//受理管理员
        repair.setUpdUser(getCurrentUserMap().get("userName"));//创建人
        IotRepairMaintenance entity=new IotRepairMaintenance();
        entity.setRepairMaintenanceId(BaseModel.returnStaticIdLong());
        entity.setGroupId(repair.getGroupId());//水泵组ID
        entity.setGroupName(repair.getGroupName());//水泵组名称
        entity.setBelongedHouse(repair.getBelongedHouse());
        entity.setBelongedCommunity(repair.getBelongedCommunity());
        entity.setRepairDeclareId(repair.getRepairDeclareId());//设备申报ID
        entity.setState(3);//待处理
        iotRepairMaintenanceService.insert(entity);
        iotRepairDeclareService.updateById(repair);
        return R.ok();
    }

    /**
     * 修改受理申报信息
     * @param acceptPerson
     * @param acceptPhone
     * @return
     */
    @ApiOperation(value = "修改受理申报信息")
    @PostMapping("/updateAcceptPerson")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="acceptPerson",value="受理人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="acceptPhone",value="受理人电话",required = true,dataType = "String",paramType="form"),
    })
    public R updateAcceptPerson(String repairDeclareId,String acceptPerson,String acceptPhone){
        parameterIsNull(repairDeclareId,"请填写设备保修申报ID");
        parameterIsNull(acceptPerson,"受理人不能为空");
        parameterIsNull(acceptPhone,"受理人电话不能为空");
        Boolean is=PhoneUtils.isPhone(acceptPhone);
        if(is==false){return  R.error(400,"受理人电话格式错误");}
        IotRepairDeclare repair=iotRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        repair.setAcceptPerson(acceptPerson);//受理人
        repair.setAcceptPhone(acceptPhone);//受理电话
        repair.setAcceptData(new Date());//受理时间
        repair.setState(3);//修改状态为已受理
        repair.setIsRead(2);//是否已读(1已读2未读)
        repair.setUpdTime(new Date());//修改时间
        repair.setUpdUser(getCurrentUserMap().get("userName"));//创建人
        iotRepairDeclareService.updateById(repair);
        return R.ok();
    }

    /**
     * 修改状态为拒绝受理
     * @param repairDeclareId
     * @return
     */
    @ApiOperation(value = "修改状态为拒绝受理")
    @PostMapping("/updateState_2")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form")
    })
    public R updateState_2(String repairDeclareId){
        parameterIsNull(repairDeclareId,"请填写设备保修申报ID");
        IotRepairDeclare repair=iotRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        repair.setState(2);//修改状态为拒绝受理
        repair.setIsRead(2);//是否已读(1已读2未读)
        repair.setUpdTime(new Date());
        repair.setUpdUser(getCurrentUserMap().get("userName"));
        iotRepairDeclareService.updateById(repair);
        return R.ok();
    }
    /**
     * 维修信息修改
     * @param repairMaintenanceId
     * @param startData
     * @param endData
     * @param state
     * @param maintenanceCosts
     * @param maintenanceDescription
     * @return
     */
    @ApiOperation(value = "维修信息修改")
    @PostMapping("/update/Maintenance")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairMaintenanceId",value="设备维修信息ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="startData",value="开始时间",required = false,dataType = "Date",paramType="form"),
            @ApiImplicitParam(name="endData",value="结束时间",required = false,dataType = "Date",paramType="form"),
            @ApiImplicitParam(name="state",value="维修状态1.维修成功2维修失败3.待处理",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="maintenanceCosts",value="维修费用",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="maintenanceDescription",value="维修描述",required = false,dataType = "String",paramType="form"),
    })
    public R updateMaintenance(Long repairMaintenanceId,String startData, String endData, Integer state, String maintenanceCosts, String maintenanceDescription){
        parameterIsNull(repairMaintenanceId,"请填写设备申报信息ID");
        IotRepairMaintenance maintenance=iotRepairMaintenanceService.selectById(repairMaintenanceId);
        if (maintenance==null){ return  R.error(400,"该测点维修信息不存在");}
        IotRepairDeclare repair=iotRepairDeclareService.selectById(maintenance.getRepairDeclareId());
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        if (repair.getState()!=3){return  R.error(400,"设备申报信息还未受理，请稍等！");}
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startData)){
            Date start = null;
            try {
                start = sdf.parse(startData);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            maintenance.setStartData(start);//开始时间
        }
        if (StringUtils.isNotBlank(endData)){
            Date end = null;
            try {
                end = sdf.parse(endData);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            maintenance.setEndData(end);//结束时间
        }
        if (null!=state){
            maintenance.setState(state);//维修状态：1维修成功2维修失败
        }
        if (StringUtils.isNotBlank(maintenanceCosts)){
            BigDecimal bd=new BigDecimal(maintenanceCosts);
            maintenance.setMaintenanceCosts(bd);//维修费用
        }
        if (StringUtils.isNotBlank(maintenanceDescription)){
            maintenance.setMaintenanceDescription(maintenanceDescription);//维修描述
        }
        repair.setTarget(1);
        repair.setIsRead(2);//是否已读(1已读2未读)
        iotRepairDeclareService.updateById(repair);
        iotRepairMaintenanceService.updateById(maintenance);
        return R.ok();
    }


    /**
     * 查询单条设备维修信息
     * @param repairMaintenanceId
     * @return
     */
    @ApiOperation(value = "查询单条设备维修信息")
    @GetMapping(value = "/seteleByMaintenance")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairMaintenanceId",value="设备维修信息ID",required = true,dataType = "Long",paramType="form"),
    })
    public R seteleByMaintenance(@RequestParam Long repairMaintenanceId){
        parameterIsNull(repairMaintenanceId,"设备保修申报ID不能为空");
        IotRepairMaintenance Maintenance= iotRepairMaintenanceService.seteleByMaintenance(repairMaintenanceId);
        return R.ok().put("data",Maintenance);
    }

    /**
     * 分页查询申报维修信息
     * @param limit
     * @param page
     * @param id
     * @return
     */
    @ApiOperation(value = "分页查询申报信息")
    @GetMapping("/declarePage")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="id",value="分区ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="查询字段",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="target",value="标识查询层级（1查询水泵组2查询物业小区水泵房3查询系统）",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="公司编码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="maintenanceName",value="查询字段(维修信息查询)",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="repairLimit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="repairPage",value="分页页数",required = false,dataType = "int",paramType="form"),
    })
    public R declarePage(Long id,int limit,int page,String name,int target,String companyCode,String maintenanceName,int repairLimit,int repairPage){
        parameterIsNull(id,"请填写分区ID");
        parameterIsNull(target,"标识是否是水泵组");
        parameterIsNull(companyCode,"请填写公司编码");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        if (repairLimit<1){repairLimit=10;}
        if (repairPage<1){repairPage=1;}
        Wrapper ew=new EntityWrapper();
        List<String> str2=new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        if (target==1){
            ew.eq("rd.group_id",id);//查询水泵组
            List<IotRepairDeclare> list=iotRepairDeclareService.selectByIotRepairIstrue(new EntityWrapper<IotRepairDeclare>().eq("rd.group_id",id).and().isNotNull("wpg.group_id"));
            if (list.size()>0){
                parameter.put("ids",id);
            }else {
                parameter.put("ids",-1);
            }
        }else if ((target==2)){
            IotAgency  agency = orgService.selectById(id);
            parameterIsNull(agency,"机构信息不存在");
            if (agency.getLevel()==2){
                ew.eq("rd.agency_id",id);//查询物业
                List<IotRepairDeclare> list=iotRepairDeclareService.selectByIotRepairIstrue(new EntityWrapper<IotRepairDeclare>().eq("rd.agency_id",id).and().isNotNull("wpg.group_id"));
                if (list.size()>0){
                    for (int x=0;x<list.size();x++){
                        str2.add(list.get(x).getGroupId().toString());
                    }
                    String ids= Joiner.on(",").join(str2);
                    parameter.put("ids",ids);
                }else {
                    parameter.put("ids",-1);
                }
            }else if (agency.getLevel()==3){
                ew.eq("rd.community_id",id);//查询小区
                List<IotRepairDeclare> list=iotRepairDeclareService.selectByIotRepairIstrue(new EntityWrapper<IotRepairDeclare>().eq("rd.community_id",id).and().isNotNull("wpg.group_id"));
                if (list.size()>0){
                    for (int x=0;x<list.size();x++){
                        str2.add(list.get(x).getGroupId().toString());
                    }
                    String ids= Joiner.on(",").join(str2);
                    parameter.put("ids",ids);
                }else {
                    parameter.put("ids",-1);
                }
            }else if (agency.getLevel()==4){
                ew.eq("rd.house_id",id);//查询水泵房
                List<IotRepairDeclare> list=iotRepairDeclareService.selectByIotRepairIstrue(new EntityWrapper<IotRepairDeclare>().eq("rd.house_id",id).and().isNotNull("wpg.group_id"));
                if (list.size()>0){
                    for (int x=0;x<list.size();x++){
                        str2.add(list.get(x).getGroupId().toString());
                    }
                    String ids= Joiner.on(",").join(str2);
                    parameter.put("ids",ids);
                }else {
                    parameter.put("ids",-1);
                }
            }else{
                return  R.error(400,"参数异常");
            }
        }else  if (target==3){
            ew.eq("rd.company_code",companyCode);//查询系统
            List<IotRepairDeclare> list=iotRepairDeclareService.selectList(new EntityWrapper<IotRepairDeclare>().eq("company_code",companyCode));
            if (list.size()>0){
                for (int x=0;x<list.size();x++){
                    str2.add(list.get(x).getGroupId().toString());
                }
                String ids= Joiner.on(",").join(str2);
                parameter.put("ids",ids);
            }else {
                parameter.put("ids",-1);
            }
        }else{
            return  R.error(400,"参数异常");
        }
        ew.and().isNotNull("wpg.group_id");
        Page<IotRepairDeclare> pageList = new Page<IotRepairDeclare>(page,limit);
        Page<IotRepairMaintenance>  pagesize=new Page<IotRepairMaintenance>(repairPage,repairLimit);
        if (StringUtils.isNotBlank(name)){
            ew.and().like("rd.group_name", name);
            ew.or().like("rd.belonged_house", name);
            ew.or().like("rd.belonged_community", name);
            ew.or().like("rd.declare_type", name);
            ew.or().like("rd.declare_person", name);
            ew.or().like("rd.declare_phone", name);
            ew.or().like("rd.accept_person", name);
            ew.or().like("rd.accept_phone", name);
            ew.or().like("rd.description", name);
        }
        if (StringUtils.isNotBlank(maintenanceName)) {
            parameter.put("name", "and (group_name like '%"+maintenanceName+"%' or belonged_house like '%"+maintenanceName+"%'" +
                    "or belonged_community like '%"+maintenanceName+"%'or maintenance_description like '%"+maintenanceName+"%')");
        }
        parameter.put("limit",repairLimit);
        parameter.put("page",(repairPage-1)*repairLimit);
        ew.orderBy("rd.declare_data desc");
        Map<String,Object>  map=new HashMap<>();
        pagesize =  iotRepairMaintenanceService.selectByPageMap(pagesize,parameter);
        pageList = iotRepairDeclareService.selectByIotRepairDeclarePage(pageList,ew);
        map.put("pageList",pageList);
        map.put("pageSize",pagesize);
        return R.ok().put("data",map);
    }

    /**
     * 分页查询维修信息
     * @param limit
     * @param page
     * @param repairDeclareId
     * @param name
     * @return
     */
    @ApiOperation(value = "分页维修信息")
    @GetMapping("/maintenancePage")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="repairDeclareId",value="申报信息ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="查询字段",required = false,dataType = "String",paramType="form"),
    })
    public R maintenancePage(int limit,int page,Long repairDeclareId,String name){
        parameterIsNull(repairDeclareId,"请填写申报信息ID");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("repairDeclareId",repairDeclareId);
        Page<IotRepairMaintenance> pageList = new Page<IotRepairMaintenance>(page,limit);
        if (StringUtils.isNotBlank(name)) {
            parameter.put("name", "and (group_name like '%"+name+"%' or belonged_house like '%"+name+"%'" +
                    "or belonged_community like '%"+name+"%'or maintenance_costs like '%"+name+"%'or maintenance_description like '%"+name+"%')");
        }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        pageList = iotRepairMaintenanceService.selectByPageList(pageList,parameter);
        return R.ok().put("data",pageList);
    }


}